//
//  DataBaseManager.m
//  YSSmartHome
//
//  Created by Yahaong on 16/8/18.
//  Copyright © 2016年 yahaong. All rights reserved.
//

#import "DataBaseManager.h"
#import "OperationModel.h"
#import "YHMarcros.h"
#import "DBHeader.h"
#import "XAISDK/XAITLV.h"
#import "ZTMessage.h"
#import "XAISDK/XAI.h"

@interface DataBaseManager ()

@end
@implementation DataBaseManager

//单例
+(instancetype)sharedManager{
    
    static DataBaseManager *manager = nil;
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        manager = [[DataBaseManager alloc] init];
    });
    return manager;
}

- (instancetype)init{
    
    if (self = [super init]) {
        
        NSString *docDir = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
        NSString *filePath = [docDir stringByAppendingPathComponent:@"ztwy.sqlite"];
        debugLogInfo(@"路径 = %@",filePath);
        _databaseQueue = [FMDatabaseQueue databaseQueueWithPath:filePath];
    }
    return self;
}

+ (void)creatTableIfNeed {
    //【注意】：以后做sql语句，()外面的参数用字符串拼，()里面的参数放在执行方法里写
    NSString *sql = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS %@ (id INTEGER PRIMARY KEY AUTOINCREMENT, apsn integer NOT NULL, luid integer NOT NULL,triggerApsn integer NOT NULL, triggerLuid integer NOT NULL, time integer NOT NULL, operation text NOT NULL);",KTable_Operation];
    [kDataBaseManager.databaseQueue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        if (![db executeUpdate:sql]) {
            debugLogInfo(@"创建%@失败",KTable_Operation);
        }
    }];
    sql = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS %@ (id INTEGER PRIMARY KEY AUTOINCREMENT, apsn integer, luid integer, time integer, type integer,value float);",KTable_Air];
    [kDataBaseManager.databaseQueue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        if (![db executeUpdate:sql]) {
           debugLogInfo(@"创建%@失败",KTable_Air);
        }
    }];
    sql = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS %@ (ID INTEGER PRIMARY KEY AUTOINCREMENT, FROMAPSN INTEGER, FROMLUID INTEGER,TOAPSN INTEGER,TOLUID INTEGER,TYPE INTEGER,ISREAD INTEGER, TIME INTEGER ,DATAS BLOD);",KTable_IMMessage];
    [kDataBaseManager.databaseQueue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        if ([db executeUpdate:sql]) {
            debugLogInfo(@"创建%@表成功",KTable_IMMessage);
        } else {
            debugLogInfo(@"创建%@表失败",KTable_IMMessage);
        }
    }];
}

/*!
 *  插入数据
 *  【注意】：？？？
 */
- (BOOL)insertOperationModel:(OperationModel *)operation{
    __block BOOL success = NO;
    NSString *sql = [NSString stringWithFormat:@"insert into %@ (apsn,luid,triggerApsn,triggerLuid,time,operation) values (?,?,?,?,?,?);",KTable_Operation];
    [self.databaseQueue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        if (![db executeUpdate:sql,
              @(operation.apsn),
              @(operation.luid),
              @(operation.triggerApsn),
              @(operation.triggerLuid),
              @(operation.time),
              operation.operation]) {
            *rollback = YES;
            return ;
        }
        success = YES;
    }];
    return success;
}


- (BOOL)insertAirWithApsn:(XAITYPEAPSN)apsn luid:(XAITYPELUID)luid time:(uint32_t)time type:(uint32_t)type value:(float)value{
    __block BOOL success = NO;
    NSString *sql = [NSString stringWithFormat:@"insert into %@ (apsn,luid,time,type,value) values (?,?,?,?,?);",KTable_Air];
    [self.databaseQueue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        if (![db executeUpdate:sql,
              @(apsn),
              @(luid),
              @(time),
              @(type),
              @(value)]) {
            *rollback = YES;
            return ;
        }
        success = YES;
    }];
    return success;
}

- (void)loadAirDataWithApsn:(uint32_t)apsn luid:(uint64_t)luid  type:(int)type complete:(CompleteBlock)block {
    NSString *sql = [NSString stringWithFormat:@"select * from %@ where apsn = %zd and luid = %zd and type = %zd ORDER BY time ASC",KTable_Air, apsn, luid,type];
    [self.databaseQueue inDatabase:^(FMDatabase *db) {
        FMResultSet *re = [db executeQuery:sql];
        NSMutableArray *arrM = [NSMutableArray array];
        while ([re next]) {
            int apsn = [re intForColumn:@"apsn"];
            uint64_t luid = [re unsignedLongLongIntForColumn:@"luid"];
            int time = [re intForColumn:@"time"];
            int type = [re intForColumn:@"type"];
            float value = [re doubleForColumn:@"value"];
            AirHistoryModel *model = [[AirHistoryModel alloc] init];
            model.apsn = apsn;
            model.luid  = luid;
            model.time = time;
            model.type = type;
            model.value = value;
            [arrM addObject:model];
        }
        block(arrM);
    }];
}

- (NSArray *)loadOperationData:(uint32_t)apsn luid:(uint64_t)luid {
    NSString *sql = [NSString stringWithFormat:@"select * from %@ where apsn = %zd and luid = %zd  ORDER BY time ASC",KTable_Operation, apsn, luid];
    NSMutableArray *arrM = [NSMutableArray array];
    [self.databaseQueue inDatabase:^(FMDatabase *db) {
        FMResultSet *re = [db executeQuery:sql];
        while ([re next]) {
            int apsn = [re intForColumn:@"apsn"];
            uint64_t luid = [re unsignedLongLongIntForColumn:@"luid"];
            int triggerApsn = [re intForColumn:@"triggerApsn"];
            uint64_t triggerLuid = [re unsignedLongLongIntForColumn:@"triggerLuid"];
            int time = [re intForColumn:@"time"];
            NSString *oper = [re stringForColumn:@"operation"];
            OperationModel *operation = [OperationModel operationWithApsn:apsn luid:luid triggerApsn:triggerApsn triggerLuid:triggerLuid time:time operation:oper];
            [arrM addObject:operation];
        }
    }];
    return arrM.copy;
}

- (void)storeIMMessagefromApsn:(uint32_t)fromApsn
                      fromLuid:(uint64_t)fromLuid
                        toApsn:(uint32_t)toApsn
                        toLuid:(uint64_t)toLuid
                          type:(uint32_t)type
                        isRead:(uint32_t)isRead
                     timestamp:(uint32_t)timestamp
                          data:(XAITLV *)tlv
{
    NSString *sql = [NSString stringWithFormat:@"INSERT INTO  %@ (FROMAPSN,FROMLUID,TOAPSN,TOLUID,TYPE,ISREAD,TIME,DATAS) VALUES (?,?,?,?,?,?,?,?);",KTable_IMMessage];
    NSData* data = [NSKeyedArchiver archivedDataWithRootObject:tlv];
    [self.databaseQueue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        if (![db executeUpdate:sql,
              @(fromApsn),
              @(fromLuid),
              @(toApsn),
              @(toLuid),
              @(type),
              @(isRead),
              @(timestamp),
              data
              ])
        {
            *rollback = YES;
            debugLogInfo(@"插入失败");
            return;
        }
        debugLogInfo(@"插入成功");
    }];
}

- (void)loadIMMessageWithApsn:(XAITYPEAPSN)apsn luid:(XAITYPELUID)luid complete:(CompleteBlock)complete
{
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE (FROMAPSN = %zd AND FROMLUID = %zd) OR (TOAPSN = %zd AND TOLUID = %zd)  ORDER BY TIME ASC",KTable_IMMessage, apsn, luid,apsn,luid];
    [self.databaseQueue inDatabase:^(FMDatabase *db) {
        FMResultSet *re = [db executeQuery:sql];
        NSMutableArray* arrayM = [NSMutableArray array];
        while ([re next]) {
            int fromApsn = [re intForColumn:@"FROMAPSN"];
            uint64_t fromLuid = [re unsignedLongLongIntForColumn:@"FROMLUID"];
            int toApsn = [re intForColumn:@"TOAPSN"];
            uint64_t toLuid = [re unsignedLongLongIntForColumn:@"TOLUID"];
            int  type = [re intForColumn:@"TYPE"];
            int  isRead = [re intForColumn:@"ISREAD"];
            int  time = [re intForColumn:@"TIME"];
            NSData *data = [re dataForColumn:@"DATAS"];
             XAITLV* tlv = data ? [NSKeyedUnarchiver unarchiveObjectWithData:data] : nil;
            NSString* text = [[NSString alloc]initWithBytes:[tlv getPayloadbyte] length:tlv.payloadlen encoding:NSUTF8StringEncoding];
        
            ZTMessage* message = [[ZTMessage alloc]initWithSenderId:[XAI luidToMobile:fromLuid] senderDisplayName:[XAI luidToMobile:fromLuid] date:[NSDate dateWithTimeIntervalSince1970:time] text:text];
                       message.fromApsn = fromApsn;
            message.fromLuid = fromLuid;
            message.toApsn = toApsn;
            message.toLuid = toLuid;
            message.type = type;
            message.time = time;
            message.tlv = tlv;
            message.isRead = isRead;
            [arrayM addObject:message];
        }
        complete(arrayM);
    }];
}

- (void)modifyUnReadMessageWithApsn:(XAITYPEAPSN)apsn luid:(XAITYPELUID)luid
{
//    update 表名 set 字段名=值 where 条件子句。如：update person set name=‘传智‘ where id=10
    
    NSString *sql = [NSString stringWithFormat:@"UPDATE %@ SET ISREAD = %zd where  FROMAPSN = %zd AND FROMLUID = %zd;",KTable_IMMessage,1,apsn,luid];
    [self.databaseQueue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        if (![db executeUpdate:sql])
        {
            debugLogInfo(@"更新%@失败",KTable_IMMessage);
        }
    }];
}
@end
